package com.mingqijia.gassafety.webserver.service.report.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.RecordDetector;
import com.mingqijia.gassafety.db.entity.auth.DictionaryItemEntry;
import com.mingqijia.gassafety.db.entity.vo.ReportAlarmDataVo;
import com.mingqijia.gassafety.db.entity.vo.ReportDeviceDataVo;
import com.mingqijia.gassafety.db.hangzhou.entity.AlertRecordSign;
import com.mingqijia.gassafety.db.mapper.AlertRecordSignMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.RecordDetectorMapper;
import com.mingqijia.gassafety.db.mapper.auth.DictionaryItemMapper;
import com.mingqijia.gassafety.shared.constant.EquipmentTypeConst;
import com.mingqijia.gassafety.shared.utils.CoordinateTransformer;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.inner.report.AlarmDataRequest;
import com.mingqijia.gassafety.webserver.request.inner.report.DeviceDataRequest;
import com.mingqijia.gassafety.webserver.response.inner.report.AlarmDataContentResponse;
import com.mingqijia.gassafety.webserver.response.inner.report.AlarmDataResponse;
import com.mingqijia.gassafety.webserver.response.inner.report.DeviceDataContentResponse;
import com.mingqijia.gassafety.webserver.response.inner.report.DeviceDataResponse;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.service.EquipmentManufacturerService;
import com.mingqijia.gassafety.webserver.service.report.ReportDataService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class ReportDataServiceImpl implements ReportDataService {
    private static final Logger log = LoggerFactory.getLogger(ReportDataServiceImpl.class);
    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    DictionaryItemMapper dictionaryItemMapper;

    @Autowired
    AlertRecordSignMapper alertRecordSignMapper;

    @Autowired
    RecordDetectorMapper recordDetectorMapper;

    @Autowired
    EquipmentManufacturerService equipmentManufacturerService;

    @Override
    public PageUtil<DeviceDataResponse> getDeviceData(DeviceDataRequest request) {
        int pageIndex = null==request.getPage()?1:request.getPage();
        int pageSize = null==request.getPageSize()?10:request.getPageSize();
        Page<ReportDeviceDataVo> page = PageHelper.startPage(pageIndex, pageSize);
        List<ReportDeviceDataVo> list =dtuMapper.getReportDeviceData(request.getSpId(),request.getDeviceId(),request.getDataType());
        if (list.isEmpty()){
            return new PageUtil<>(pageIndex, pageSize, page.getTotal(), new ArrayList<>());
        }
        List<DeviceDataResponse> respList = new ArrayList<>();
        Map<String,AlarmSupplierListVo> supplierListVoMap = equipmentManufacturerService.queryMap();
        Map<String,String> operatorMap = getDictMap("Operator");
        String yhStreetStr = "{\"330105015\":\"潮鸣街道\",\"330105016\":\"朝晖街道\",\"330105017\":\"文辉街道\",\"330105018\":\"东新街道\",\"330105019\":\"石桥街道\",\"330110005\":\"五常街道\",\"330110009\":\"仁和街道\",\"330110010\":\"良渚街道\",\"330110011\":\"闲林街道\",\"330110012\":\"仓前街道\",\"330110013\":\"余杭街道\",\"330110014\":\"中泰街道\",\"330110109\":\"径山镇\",\"330110110\":\"瓶窑镇\",\"330110111\":\"鸬鸟镇\",\"330110112\":\"百丈镇\"}";

        Map yhMap =JSON.parseObject(yhStreetStr,Map.class);
        for (ReportDeviceDataVo item:list){
            DeviceDataResponse respItem = new DeviceDataResponse();
            if(StringUtils.isNotEmpty(item.getName())){
                respItem.setDeviceName(item.getName());
            }else {
                respItem.setDeviceName(EquipmentTypeConst.equipmentTypeMaps.getOrDefault(item.getEquipmentType(), ""));
            }
            respItem.setDeviceCode(item.getIMEI());
            respItem.setDeviceTypeCode("J1-001");
            respItem.setDeviceTypeName("报警器");
            if ( null!=supplierListVoMap && supplierListVoMap.containsKey(item.getEquipmentManufacturer())
            && null!=supplierListVoMap.get(item.getEquipmentManufacturer()) ){
                respItem.setManufacturer(supplierListVoMap.get(item.getEquipmentManufacturer()).getMsName());
            }else{
                respItem.setManufacturer("未知");
            }
            Map<String,Integer> cmMap = new HashMap<>();
            cmMap.put("NB",1);
            cmMap.put("LoRa",2);
            cmMap.put("2G",3);
            cmMap.put("3G",3);
            cmMap.put("4G",3);
            cmMap.put("WIFI",4);
            cmMap.put("LAN",5);
            //cmMap.put("Cat.1",5);
            respItem.setLinkType(cmMap.getOrDefault(item.getCommunicationMode(),3));
            respItem.setDistrictCode(null==item.getAdcode()?"":item.getAdcode());
            respItem.setDistrictName(null==item.getDistrict()?"":item.getDistrict());
            String streetCode = null==item.getTowncode()?"":item.getTowncode();
            String streetName = null==item.getTownship()?"":item.getTownship();
            if ( "c2c3f0867b0c42079c0213d0a247a231".equals(request.getSpId()) ){
                respItem.setProvinceCode("330000");
                respItem.setProvinceName("浙江省");
                respItem.setCityCode("330100");
                respItem.setCityName("杭州市");
                if( StringUtils.isNotEmpty(streetCode) ){
                    streetName = yhMap.containsKey(streetCode)?yhMap.get(streetCode).toString():streetName;
                }
                respItem.setStreetCode(streetCode);
                respItem.setStreetName(streetName);

                if (StringUtils.isEmpty(respItem.getDistrictCode())){
                    respItem.setDistrictCode("330110");
                    respItem.setDistrictName("余杭区");
                }
                if (StringUtils.isEmpty(respItem.getStreetCode())){
                    respItem.setStreetCode("330110005");
                    respItem.setStreetName("五常街道");
                }
                if ( !(item.getLng() != null && item.getLat() != null
                        && item.getLng()>0 && item.getLat()>0) ) {
                    item.setLng(120.055853);
                    item.setLat(30.2535480623);
                    //无经纬度无地址时补充地址
                    if (StringUtils.isEmpty(item.getInstallationAddress())){
                        item.setInstallationAddress("浙江省杭州市余杭区五常大道西溪印象城");
                    }
                }
            }else{
                if( null!=request.getIsTrimStreetCode() && request.getIsTrimStreetCode() &&
                        StringUtils.isNotEmpty(streetCode) && streetCode.length()>3 ) {
                    streetCode = streetCode.substring(0, streetCode.length() - 3);
                }
                respItem.setProvinceCode("");
                respItem.setProvinceName("");
                respItem.setCityCode(item.getCitycode());
                respItem.setCityName(item.getCity());
                respItem.setStreetCode(streetCode);
                respItem.setStreetName(streetName);
            }
            respItem.setAddress(null==item.getInstallationAddress()?"":item.getInstallationAddress());
            if (item.getLng() != null && item.getLat() != null && item.getLng()>0 && item.getLat()>0) {
                double[] doubles = CoordinateTransformer.transformBD09ToWGS84(
                        Double.parseDouble(item.getLng() + ""), Double.parseDouble(item.getLat() + ""));
                respItem.setLng(String.valueOf(doubles[0]));
                respItem.setLat(String.valueOf(doubles[1]));
            }else{
                respItem.setLng("0");
                respItem.setLat("0");
            }
            if( null == item.getDeviceStatus() ){
                item.setDeviceStatus(0);
            }
            if( 0 == item.getDeviceStatus() ){
                respItem.setStatus(0);
            }else{
                respItem.setStatus(1);
            }
            respItem.setState(1);
            if( item.getIsDeleted() ){
                respItem.setState(-1);
                respItem.setStatus(3);
            }
            Random random = new Random();
            int randomInt = random.nextInt(100);
            respItem.setTransmissionIntercal(2*60*60+randomInt);
            respItem.setDept("住建");
            respItem.setVersion("V1.0.1");
            respItem.setScene1("r-0");
            respItem.setScene2("r-40");
            respItem.setScene3("r-402");
            respItem.setMessageType(1);
            try {
                if ( null == item.getStateUpdateAt() || item.getUpdateAt().getTime() > item.getStateUpdateAt().getTime() ) {
                    respItem.setReportTime(DateUtil.format(item.getUpdateAt(), "yyyy-MM-dd HH:mm:ss"));
                } else {
                    respItem.setReportTime(DateUtil.format(item.getStateUpdateAt(), "yyyy-MM-dd HH:mm:ss"));
                }
            }catch (Exception e){
                respItem.setReportTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            }
            respItem.setProductKey(null==item.getEquipmentModel()?"":item.getEquipmentModel());
            respItem.setInstallDate(null==item.getInstallDate()?"":item.getInstallDate());

            List<DeviceDataContentResponse> content = new ArrayList<>();
            DeviceDataContentResponse deviceDataContentResponse = new DeviceDataContentResponse();
            deviceDataContentResponse.setTopic("operators");
            deviceDataContentResponse.setName("运营商");
            deviceDataContentResponse.setDataType(2);
            deviceDataContentResponse.setUpdateValue(operatorMap.getOrDefault(item.getOperators(),item.getOperators()));
            deviceDataContentResponse.setUnit("");
            content.add(deviceDataContentResponse);

            deviceDataContentResponse = new DeviceDataContentResponse();
            deviceDataContentResponse.setTopic("iccid");
            deviceDataContentResponse.setName("iccid");
            deviceDataContentResponse.setDataType(2);
            deviceDataContentResponse.setUpdateValue(item.getIccid());
            deviceDataContentResponse.setUnit("");
            content.add(deviceDataContentResponse);

            if( null!=item.getConcentration() && item.getConcentration()>0 ){
                deviceDataContentResponse = new DeviceDataContentResponse();
                deviceDataContentResponse.setTopic("concentration");
                deviceDataContentResponse.setName("气体浓度值");
                deviceDataContentResponse.setDataType(0);
                deviceDataContentResponse.setUpdateValue(String.valueOf(item.getConcentration()));
                deviceDataContentResponse.setUnit("%LEL");
                content.add(deviceDataContentResponse);
            }
            respItem.setContent(content);
            respList.add(respItem);
        }
        PageUtil pageInfo = new PageUtil<>(pageIndex, pageSize, page.getTotal(), respList);
        return pageInfo;
    }

    @Override
    public PageUtil<AlarmDataResponse> getAlarmData(AlarmDataRequest request) {
        int pageIndex = null==request.getPage()?1:request.getPage();
        int pageSize = null==request.getPageSize()?10:request.getPageSize();
        Page<ReportAlarmDataVo> page = PageHelper.startPage(pageIndex, pageSize);
        List<ReportAlarmDataVo> list =dtuMapper.getReportAlarmData(request.getSpId(),request.getDeviceId(),request.getHistoryAlarmId());
        if (list.isEmpty()){
            return new PageUtil<>(pageIndex, pageSize, page.getTotal(), new ArrayList<>());
        }
        List<AlarmDataResponse> respList = new ArrayList<>();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (ReportAlarmDataVo item : list){
            try {
                LambdaQueryWrapper<RecordDetector> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.or().eq(RecordDetector::getIsDeleted, 0)
                        .eq(RecordDetector::getDeviceId, item.getId())
                        .eq(RecordDetector::getRecordAt, item.getCreatedAt())
                        .eq(RecordDetector::getSpId, request.getSpId())
                        .isNotNull(RecordDetector::getAlertType)
                        .orderByDesc(RecordDetector::getId);
                List<RecordDetector> recordDetectors = recordDetectorMapper.selectList(queryWrapper1);
                if(!recordDetectors.isEmpty()){
                    item.setAlertType(recordDetectors.get(0).getAlertType());
                    item.setConcentration(recordDetectors.get(0).getConcentration());
                    item.setGasType(recordDetectors.get(0).getGasType());
                }

                AlarmDataResponse alarmDataResponse = new AlarmDataResponse();
                alarmDataResponse.setDeviceCode(item.getId());
                alarmDataResponse.setMessageType(2);
                alarmDataResponse.setReportTime(DateUtil.format(item.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"));
                //报警类型 0-报警恢复 1-低限报警 2-高限报警 3-变化监测 5-报警
                Map<Integer, String> alertTypeMap = new HashMap<>();
                alertTypeMap.put(0, "报警恢复");
                alertTypeMap.put(1, "低限报警");
                alertTypeMap.put(2, "高限报警");
                alertTypeMap.put(3, "变化监测");
                alertTypeMap.put(5, "报警");
                String alarmCode = String.valueOf(item.getCreatedAt().getTime()/1000);
                alarmDataResponse.setAlarmCode(alarmCode);
                if( null!=item.getAlertType() ){
                    alarmDataResponse.setAlarmName(alertTypeMap.getOrDefault(item.getAlertType(), "变化监测"));
                }else{
                    alarmDataResponse.setAlarmName("变化监测");
                }

                if (0 == item.getAppealStatus()) {
                    alarmDataResponse.setReportType(1);
                    respList.add(alarmDataResponse);
                    continue;
                } else {
                    alarmDataResponse.setReportType(2);
                }

                LambdaQueryWrapper<AlertRecordSign> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.or().eq(AlertRecordSign::getIsDeleted, 0)
                        .eq(AlertRecordSign::getIMEI, item.getId())
                        .eq(AlertRecordSign::getAlertTime, item.getCreatedAt())
                        .orderByDesc(AlertRecordSign::getId);
                List<AlertRecordSign> alertRecordSigns = alertRecordSignMapper.selectList(queryWrapper);
                int reportType = 0;
                if (!alertRecordSigns.isEmpty()) {
                    reportType = alertRecordSigns.get(0).getReportType();
                }
                int alarmStatus = 0;
                int alarmLevel = 2;
                if (reportType == 1) {
                    alarmStatus = 3;//误报
                    alarmLevel = 4;
                } else if (0 != item.getAppealStatus() &&
                        (2 == item.getAppealStatus() || 3 == item.getAppealStatus() || 5 == item.getAppealStatus())) {
                    alarmStatus = 2;//已完成
                } else if (0 != item.getAppealStatus() &&
                        (1 == item.getAppealStatus() || 4 == item.getAppealStatus())) {
                    alarmStatus = 1;//处理中
                } else if (0 != item.getAppealStatus()) {
                    alarmStatus = 9;//无需处理
                }
                alarmDataResponse.setAlarmStatus(alarmStatus);
                if (null != item.getAppealTime()) {
                    alarmDataResponse.setDealTime(DateUtil.format(item.getAppealTime(), "yyyy-MM-dd HH:mm:ss"));

                }
                alarmDataResponse.setDept("");
                //处理人信息
                if (!StringUtils.isEmpty(item.getUserName()) && !StringUtils.isEmpty(item.getUserAccount())) {
                    alarmDataResponse.setHandler(item.getUserName() + "(" + item.getUserAccount() + ")");
                } else if (StringUtils.isEmpty(item.getUserName()) && !StringUtils.isEmpty(item.getUserAccount())) {
                    alarmDataResponse.setHandler(item.getUserAccount());
                } else if (!StringUtils.isEmpty(item.getUserName()) && StringUtils.isEmpty(item.getUserAccount())) {
                    alarmDataResponse.setHandler(item.getUserName());
                }
                alarmDataResponse.setExplanation(item.getAppealResult());
                List<AlarmDataContentResponse> warnMessage = new ArrayList<>();
                if (alarmStatus > 0) {
                    AlarmDataContentResponse alarmDataContentResponse = new AlarmDataContentResponse();
                    alarmDataContentResponse.setTopic("alert");
                    alarmDataContentResponse.setName("设备告警");
                    alarmDataContentResponse.setAlarmCode(alarmCode);
                    alarmDataContentResponse.setAlarmType(2);
                    alarmDataContentResponse.setAlarmLevel(alarmLevel);

                    LocalDateTime alarmTime = LocalDateTime.parse(DateUtil.format(item.getCreatedAt(), "yyyy-MM-dd HH:mm:ss"),pattern);
                    LocalDateTime appealTime = LocalDateTime.parse(DateUtil.format(item.getAppealTime(), "yyyy-MM-dd HH:mm:ss"),pattern);
                    Duration duration = Duration.between(alarmTime, appealTime);
                    long days = duration.toDays();
                    long hours = duration.toHours();
                    long weeks = duration.toDays() / 7;
                    if (hours < 24) {
                        alarmDataContentResponse.setDealTimeUnit(1);
                        alarmDataContentResponse.setDealTime(Math.max((int) hours,1));
                    } else if (days < 6) {
                        alarmDataContentResponse.setDealTimeUnit(2);
                        alarmDataContentResponse.setDealTime((int) days);
                    } else {
                        alarmDataContentResponse.setDealTimeUnit(3);
                        alarmDataContentResponse.setDealTime((int) weeks);
                    }

                    warnMessage.add(alarmDataContentResponse);
                }

                alarmDataResponse.setWarnMessage(warnMessage);

                respList.add(alarmDataResponse);
            }catch (Exception e){
                log.error("获取设备告警数据报错",e);
            }
        }
        PageUtil pageInfo = new PageUtil<>(pageIndex, pageSize, page.getTotal(), respList);
        return pageInfo;
    }

    public Map<String,String> getDictMap(String dictCode){
        LambdaQueryWrapper<DictionaryItemEntry> dictionaryQueryWrapper = new LambdaQueryWrapper<>();
        dictionaryQueryWrapper.eq(DictionaryItemEntry::getDictCode,dictCode)
                .eq(DictionaryItemEntry::getIsDeleted,0)
                .eq(DictionaryItemEntry::getSpId , 0);
        List<DictionaryItemEntry> dictionaryItemEntries = dictionaryItemMapper.selectList(dictionaryQueryWrapper);
        Map<String,String> dictMap = new HashMap<>();
        for (DictionaryItemEntry dictionaryItemEntry : dictionaryItemEntries){
            dictMap.put(dictionaryItemEntry.getValue(),dictionaryItemEntry.getAlias());
        }
        return dictMap;
    }
}
